package org.wu.framework.lazy.orm.database.sql.expand.database.persistence.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wu.framework.lazy.database.datasource.proxy.connection.LazyProxyConnection;
import org.wu.framework.lazy.orm.database.sql.expand.database.persistence.method.LazyOperationMethod;

import java.sql.SQLException;

/**
 * 代理对象执行方法
 */
public abstract class AbstractLazyOperationProxyInvocationHandler extends AbstractLazyOperationProxyRetryInvocationHandler {

    Logger log = LoggerFactory.getLogger(AbstractLazyOperationProxyInvocationHandler.class);

    /**
     * 获取当前连接
     *
     * @return 数据当前连接
     */
    abstract LazyProxyConnection determineConnection() throws SQLException;

    /**
     * 执行方法
     *
     * @param lazyOperationMethod 需要执行的方法
     * @param args                方法参数
     * @return 执行结果
     */
    public Object doInvoke(LazyOperationMethod lazyOperationMethod, Object[] args) throws Exception {
        LazyProxyConnection connection = null;
        boolean isConnectionTransactional = false;

        boolean autoCommit = true;

        try {
            // 切换数据库
            connection = determineConnection();
            if (connection.isClosed()) {
                log.error("this.connection  关闭了");
            }
            switchSchema(connection);
            isConnectionTransactional = connection.isConnectionTransactional();
            autoCommit = connection.getAutoCommit();


            // 判断不是事物重新获取链接
            final Object execute = lazyOperationMethod.execute(connection, args);
            // 是否提交
            if (isConnectionTransactional && autoCommit) {
                log.debug("Committing JDBC Connection [" + connection + "]");
                connection.commit();
            }
            return execute;
        } catch (Exception exception) {
            // 事物回滚
            if (connection != null && isConnectionTransactional && autoCommit) {
                log.debug("Rolling back JDBC Connection [" + connection + "]");
                connection.rollback();
            }
            //
            exception.printStackTrace();
            throw exception;
        } finally {
            // 释放链接
            if (connection != null && autoCommit) {
                connection.connectionClose();
            }

        }
    }
}
